import Vue from 'vue'
import VueRouter from 'vue-router'
import detail from '@/views/detail'
import layout from '@/views/layout'
import login from '@/views/login'
import register from '@/views/register'
// 以下是导入二级
import article from '@/views/article'
import collect from '@/views/collect'
import like from '@/views/like'
import user from '@/views/user'

Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/article' },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      { name: 'article', path: 'article', component: article },
      { name: 'collect', path: 'collect', component: collect },
      { name: 'like', path: 'like', component: like },
      { name: 'user', path: 'user', component: user }
    ]
  },
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'reg',
    path: '/register',
    component: register
  },
  {
    name: 'detail',
    path: '/detail',
    component: detail
  }
]

const router = new VueRouter({
  routes
})

// 白名单
const whiteList = ['/login', '/register']

import store from '@/store'
import { Toast } from 'vant'
// 全局前置守卫
// 这个回调函数是即将进入到某个路由之前触发
// to:    去哪，   得到的是路由对象，里面有这个路由的相关信息，比如路径和参数等
// from： 从哪来， 得到的是路由对象
// next:  是一个函数，叫放行函数，调用它就代表放行，不调用不放行
//          它也可以放行到别的页面
router.beforeEach((to, from, next) => {
  // to.path就是你要去的页面的路径
  // 判断白名单里，是否包含这个路径，如果代表可以直接放行
  if (whiteList.includes(to.path)) {
    next()
  } else {
    // 代表不在白名单，判断有没有登录
    if (store.state.token) {
      next()
    } else {
      // 弹出提示
      Toast('请先登录')
      next('/login')
    }
  }
})

export default router
